//
//  SentenceToSenPlayVC.swift
//  Game
//
//  Created by woniu on 2025/9/12.
//

import Foundation
import UIKit
import SnapKit

class SentenceToSenPlayVC: BaseVC {
    public var gameModel:GameModel!
    //题目列表数据源
    private var topicItemList:[SentenceItem] = []
    //答案列表数据源
    private var answerItemList:[SentenceItem] = []
    
    // UI
    private let leftTable = UITableView()
    private let centerTable = UITableView()
    private let rightTable = UITableView()
    private let bottomContainer = UIView()
    private let resetButton = UIButton(type: .system)
    private let checkButton = UIButton(type: .system)
    private var isSyncingScroll = false
    private var cellRealH:CGFloat = 60
    private var isNeedShowResult = false
    
    override func viewDidLoad() {
        super.viewDidLoad()
        view.backgroundColor = .black
        createDataSource()
        setupUI()
    }
    
    override func viewDidLayoutSubviews() {
        super.viewDidLayoutSubviews()
        //屏幕旋转后重新计算高度
        cellRealH = SentencePlayCardCell.getMaxCellHeight(screenW:leftTable.width, items: topicItemList)
        self.leftTable.reloadData()
        self.rightTable.reloadData()
    }
    
    /// 创建数据源inputItemList
    private func createDataSource(){
        topicItemList.removeAll()
        answerItemList.removeAll()
        if let itemList = gameModel?.jsonData.getArrayFromJSONString() {
            for item in itemList{
                if let itemDic = item as? [String:Any]{
                    let topic = SentenceItem.deserialize(from: itemDic) ?? SentenceItem()
                    let answer = SentenceItem.deserialize(from: itemDic) ?? SentenceItem()
                    topicItemList.append(topic)
                    answerItemList.append(answer)
                }
            }
        }
        answerItemList.shuffle()
    }
    
    private func setupUI(){
        
        [leftTable, centerTable, rightTable].forEach { t in
            t.backgroundColor = .clear
            t.separatorStyle = .none
            t.alwaysBounceVertical = true
            t.showsVerticalScrollIndicator = true
            view.addSubview(t)
            t.register(SentencePlayCardCell.self, forCellReuseIdentifier: SentencePlayCardCell.reuseIdentifier)
            t.dataSource = self
            t.delegate = self
        }
        
        // center table uses simple cell
        centerTable.register(UITableViewCell.self, forCellReuseIdentifier: "indexCell")
        centerTable.register(IndexBarCell.self, forCellReuseIdentifier: IndexBarCell.reuseIdentifier)
        
        // right table allows editing for move
        rightTable.isEditing = true
        rightTable.allowsSelectionDuringEditing = true
        
        
        centerTable.snp.makeConstraints { make in
            make.top.equalTo(backButton.snp.bottom)
            make.bottom.equalToSuperview().offset(-60)
            make.width.equalTo(40)
            make.centerX.equalToSuperview()
        }
        
        
        leftTable.snp.makeConstraints { make in
            make.top.equalTo(centerTable.snp.top)
            make.bottom.equalTo(centerTable.snp.bottom)
            make.left.equalToSuperview()
            make.right.equalTo(centerTable.snp.left)
        }
        
        rightTable.snp.makeConstraints { make in
            make.top.equalTo(leftTable.snp.top)
            make.bottom.equalTo(leftTable.snp.bottom)
            make.right.equalToSuperview()
            make.left.equalTo(centerTable.snp.right)
        }
        
        // bottom buttons
        view.addSubview(bottomContainer)
        bottomContainer.snp.makeConstraints { make in
            make.left.right.equalToSuperview()
            make.bottom.equalToSuperview()
            make.height.equalTo(50)
        }
        
        resetButton.setImage(UIImage(named: "重置_刷新"), for: .normal)
        resetButton.imageView?.contentMode = .scaleAspectFit
        resetButton.tintColor = .white
        resetButton.addTarget(self, action: #selector(onReset), for: .touchUpInside)
        bottomContainer.addSubview(resetButton)
        
        checkButton.setImage(UIImage(named: "检查_白色"), for: .normal)
        checkButton.tintColor = .white
        checkButton.imageView?.contentMode = .scaleAspectFit
        checkButton.addTarget(self, action: #selector(onCheck), for: .touchUpInside)
        bottomContainer.addSubview(checkButton)
        
        checkButton.snp.makeConstraints { make in
            make.right.equalToSuperview().offset(-20)
            make.centerY.equalToSuperview()
            make.height.equalTo(44)
            make.width.equalTo(44)
        }
        resetButton.snp.makeConstraints { make in
            make.right.equalTo(checkButton.snp.left).offset(-20)
            make.centerY.equalToSuperview()
            make.height.equalTo(44)
            make.width.equalTo(44)
        }
        
        
        // sync scrolls
        leftTable.addObserver(self, forKeyPath: "contentOffset", options: .new, context: nil)
        centerTable.addObserver(self, forKeyPath: "contentOffset", options: .new, context: nil)
        rightTable.addObserver(self, forKeyPath: "contentOffset", options: .new, context: nil)
    }
    
    deinit {
        leftTable.removeObserver(self, forKeyPath: "contentOffset")
        centerTable.removeObserver(self, forKeyPath: "contentOffset")
        rightTable.removeObserver(self, forKeyPath: "contentOffset")
    }
    
    // KVO observe for scroll sync
    override func observeValue(forKeyPath keyPath: String?, of object: Any?, change: [NSKeyValueChangeKey : Any]?, context: UnsafeMutableRawPointer?) {
        guard keyPath == "contentOffset" else { return }
        guard let table = object as? UITableView else { return }
        if isSyncingScroll { return }
        isSyncingScroll = true
        let offset = table.contentOffset
        if table != leftTable && leftTable.contentOffset != offset { leftTable.contentOffset = offset }
        if table != centerTable && centerTable.contentOffset != offset { centerTable.contentOffset = offset }
        if table != rightTable && rightTable.contentOffset != offset { rightTable.contentOffset = offset }
        isSyncingScroll = false
    }
    
    @objc private func onReset(){
        topicItemList.shuffle()
        answerItemList.shuffle()
        isNeedShowResult = false
        leftTable.reloadData()
        centerTable.reloadData()
        rightTable.reloadData()
    }
    
    @objc private func onCheck(){
        isNeedShowResult = true
        rightTable.reloadData()
    }
}

extension SentenceToSenPlayVC: UITableViewDataSource, UITableViewDelegate {
    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return topicItemList.count
    }
    
    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let idx = indexPath.row
        if tableView == leftTable {
            let cell = tableView.dequeueReusableCell(withIdentifier: SentencePlayCardCell.reuseIdentifier, for: indexPath) as! SentencePlayCardCell
            cell.updateUILeft(item: topicItemList[idx],index: idx)
            return cell
        } else if tableView == rightTable {
            let cell = tableView.dequeueReusableCell(withIdentifier: SentencePlayCardCell.reuseIdentifier, for: indexPath) as! SentencePlayCardCell
            cell.showsReorderControl = true
            cell.updateUIRight(item: answerItemList[idx],index: idx)
            if isNeedShowResult == true{
                let isCorrect = topicItemList[idx].answer == answerItemList[idx].answer
                cell.onCheckAndShow(index: indexPath.row, isCorrect: isCorrect)
            }
            return cell
        } else {
            let cell = tableView.dequeueReusableCell(withIdentifier: IndexBarCell.reuseIdentifier, for: indexPath) as! IndexBarCell
            cell.titleLabel.text = "\(indexPath.row+1)"
            return cell
        }
    }
    
    func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
        // 保持左右卡片大小一致
        return cellRealH
    }
    
    // enable move only for right table
    func tableView(_ tableView: UITableView, canMoveRowAt indexPath: IndexPath) -> Bool {
        return tableView == rightTable
    }
    
    func tableView(_ tableView: UITableView, shouldIndentWhileEditingRowAt indexPath: IndexPath) -> Bool {
        // avoid indentation for clean layout
        return false
    }
    
    func tableView(_ tableView: UITableView, moveRowAt sourceIndexPath: IndexPath, to destinationIndexPath: IndexPath) {
        guard tableView == rightTable else { return }
        let item = answerItemList.remove(at: sourceIndexPath.row)
        answerItemList.insert(item, at: destinationIndexPath.row)
    }
    
    // disallow editing style (no delete)
    func tableView(_ tableView: UITableView, editingStyleForRowAt indexPath: IndexPath) -> UITableViewCell.EditingStyle {
        return .none
    }
}
